// blv格式的转换器
package converter

import (
	"bytes"
	"log"
	"os"
	"os/exec"
	"path/filepath"
)

func init() {
	Register(BLV, "blv", BlvConverter)
}

func BlvConverter(cacheVideoDir *CacheVideoDir, targetPath, temp string) {
	path := filepath.Join(targetPath, cacheVideoDir.Title)
	if len(cacheVideoDir.FileInfo) == 0 || !MkdirAllDir(path) {
		return
	}
	videoName := ""
	for _, videoInfo := range cacheVideoDir.FileInfo {
		videoName = filepath.Join(path, videoInfo.Title)
		videoName = videoName + videoInfo.Suffix
		config := createConfig(filepath.Join(temp, videoInfo.Title), videoInfo.Videos)
		invokeBlv(config, videoName)
	}
}

func createConfig(configPath string, video []string) (path string) {
	configPath += ".txt"
	file, e := os.OpenFile(configPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
	if e != nil {
		log.Printf("创建config文件【%s】失败:%s\n", configPath, e.Error())
		return ""
	}
	defer file.Close()
	for _, v := range video {
		_, e := file.WriteString("file '" + v + "'\n")
		if e != nil {
			log.Printf("写入config文件【%s】失败:%s\n", configPath, e.Error())
			return ""
		}
	}
	return configPath
}

func invokeBlv(config, name string) {
	defer func() {
		remove := os.Remove(config)
		if remove != nil {
			log.Printf("删除config文件【%s】失败:%s\n", config, remove.Error())
		}
	}()
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	cmd := exec.Command("ffmpeg", "-f", "concat", "-safe", "0", "-i", config, "-c", "copy", name)
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err != nil {
		log.Println("执行命令失败:", err.Error())
		log.Println("--- stdout ---")
		log.Println(stdout.String())
		log.Println("--- stderr ---")
		log.Println(stderr.String())
		return
	}
}
